/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { Effect, Reducer, history } from 'umi';
import { setStorage, checkInMicroMessenger } from '@/utils/utils';
import { setAuthority } from '@/utils/authority';
import { getInfo, getManager } from '@/services/admin/editMenu/index';
import { getAuthRoute, getRouteArr } from '@/utils/admin/menu';

interface ManagerInfo {
  name?: string;
  mobile?: string;
}

export interface CurrentUser {
  name?: string;
  mobile?: string;
  userid?: string;
  vendor?: string;
  unreadCount?: number;
  managerInfo?: ManagerInfo;
  isManager?: boolean;
  userInfo?: {
    menu_list: (string | number)[];
  };
}

export interface UserModelState {
  currentUser?: CurrentUser;
  isManager?: boolean;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
  };
}

// 本地登录信息key
export const userInfoKey = 'userInfo';

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
    isManager: false,
  },

  effects: {
    *fetchCurrent({ payload }, { put, call }) {
      const {
        location: { pathname = '/' },
      } = history;
      if (checkInMicroMessenger() || /authPhone/.test(pathname)) return;
      if (payload && payload.callBack) {
        payload.callBack();
      }
      const { data: userInfo } = yield call(getInfo, payload);
      const { data: managerInfo } = yield call(getManager, payload);
      const { id: userId } = userInfo || {};
      const { id: managerId } = managerInfo || {};
      if (!userId || !managerId) return;
      let isManager = false;
      // console.log('userInfo', userInfo);
      let menuList = userInfo.menu_list || [];
      if (userId === managerId) {
        isManager = true;
        menuList = Array.from(new Set(getRouteArr().map((item: any) => item.authKey)));
      }
      const payloadDatas = getAuthRoute(menuList); //以authKey获取需要的权限配置信息
      const currentUser = {
        vendor: payloadDatas,
        managerInfo,
        userInfo,
        isManager,
      };
      yield put({
        type: 'saveCurrentUser',
        payload: currentUser,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      const currentUser = action.payload || {};
      const { vendor = '', ...userInfo } = currentUser;
      setAuthority(vendor);
      setStorage(userInfoKey, userInfo);
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
  },
};

export default UserModel;
